<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handlerInput" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="departmentList" :props="defaultProps" default-expand-all highlight-current :expand-on-click-node="false" @current-change="selectNode" />
      </div>
      <div class="right">
        <el-row class="operate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="dispatchRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="onDelete(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="onChangePage"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-dialog.sync="showDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="dispatchRoleSuccess">确认</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import FileSaver from 'file-saver'
import { departmentGetService } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { employeeListService, employeeExportService, employeeDeleteService, employeeDetailService, employeeAssaignRoleService } from '@/api/employee'
import { roleEnabledListService } from '@/api/role'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      departmentList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      queryParams: {
        // 查询参数：部门id
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: ''
      },
      list: [],
      total: 0,
      showDialog: false,
      showRoleDialog: false, // 分配角色对话框的显示状态
      roleList: [], // 角色列表
      roleIds: [], // 选中的角色id
      currentNodeId: null // 当前节点id
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    async getDepartmentList() {
      this.departmentList = transListToTreeData(await departmentGetService(), 0)
      this.queryParams.departmentId = this.departmentList[0].id
      // 组件渲染数据是异步的，因此需要nextTick
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId) // 设置当前选中的部门id
      })
      this.getEmployeeList() // 此时，查询参数已经更新，可以获取员工列表
    },
    selectNode(data) {
      // data 是当前选中的节点数据
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1 // 切换部门，重置页码
      this.getEmployeeList() // 切换部门，更新查询参数，重新获取员工列表
    },
    async getEmployeeList() {
      const { rows, total } = await employeeListService(this.queryParams)
      this.list = rows
      this.total = total
    },
    onChangePage(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },
    handlerInput() {
      // console.log(this.queryParams.keyword)
      clearTimeout(this.timer) // 清除定时器
      // 节流，防止频繁请求
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async exportEmployee() {
      // 导出excel
      // 1. 获取excel数据
      const res = await employeeExportService()
      // console.log(res)
      // 将Blob对象转为可以直接下载的文件,使用FileSaver.js
      FileSaver.saveAs(res, '员工信息表.xls')
    },
    async onDelete(id) {
      // 删除员工
      await employeeDeleteService(id)
      this.$message({
        type: 'success',
        message: '删除成功'
      })
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
    },
    async dispatchRole(id) {
      // 分配角色
      this.currentNodeId = id
      // 获取当前员工的角色列表
      const { roleIds } = await employeeDetailService(id)
      this.roleIds = roleIds
      this.roleList = await roleEnabledListService()
      // 获取完当前员工的角色列表之后，再打开分配角色对话框，这样才不会出现角色列表为空的情况
      this.showRoleDialog = true
    },
    async dispatchRoleSuccess() {
      // 确认分配角色
      await employeeAssaignRoleService({
        id: this.currentNodeId,
        roleIds: this.roleIds
      })
      this.$message({
        type: 'success',
        message: '分配成功'
      })
      this.showRoleDialog = false
      this.getEmployeeList()
    }
  }

}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .operate-tools {
      margin-bottom: 20px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
</style>
